import { defineStore } from 'pinia'
import { authApi } from '@/api/auth'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo') || 'null'),
    permissions: JSON.parse(localStorage.getItem('permissions') || '[]'),
  }),
  
  getters: {
    isLoggedIn: (state) => !!state.token,
    username: (state) => state.userInfo?.username || '',
    avatar: (state) => state.userInfo?.avatar || '',
    roles: (state) => state.userInfo?.roles || [],
  },
  
  actions: {
    // 登录
    async login(loginForm) {
      try {
        // 模拟登录逻辑 - 临时用于前端测试
        if (loginForm.username === 'admin' && loginForm.password === '123456') {
          const mockResponse = {
            token: 'mock-token-' + Date.now(),
            userInfo: {
              id: 1,
              username: 'admin',
              email: 'admin@example.com',
              avatar: '',
              roles: [{ id: 1, name: '超级管理员', code: 'admin' }]
            },
            permissions: ['user.view', 'user.create', 'user.update', 'user.delete', 'role.view', 'role.create', 'role.update', 'role.delete']
          }
          
          const { token, userInfo, permissions } = mockResponse
          
          this.token = token
          this.userInfo = userInfo
          this.permissions = permissions
          
          // 保存到本地存储
          localStorage.setItem('token', token)
          localStorage.setItem('userInfo', JSON.stringify(userInfo))
          localStorage.setItem('permissions', JSON.stringify(permissions))
          
          return mockResponse
        } else if (loginForm.username === 'user' && loginForm.password === '123456') {
          const mockResponse = {
            token: 'mock-token-' + Date.now(),
            userInfo: {
              id: 2,
              username: 'user',
              email: 'user@example.com',
              avatar: '',
              roles: [{ id: 2, name: '普通用户', code: 'user' }]
            },
            permissions: ['user.view']
          }
          
          const { token, userInfo, permissions } = mockResponse
          
          this.token = token
          this.userInfo = userInfo
          this.permissions = permissions
          
          // 保存到本地存储
          localStorage.setItem('token', token)
          localStorage.setItem('userInfo', JSON.stringify(userInfo))
          localStorage.setItem('permissions', JSON.stringify(permissions))
          
          return mockResponse
        } else {
          throw new Error('用户名或密码错误')
        }
        
        // TODO: 后端API开发完成后，替换为真实的API调用
        // const response = await authApi.login(loginForm)
        // const { token, userInfo, permissions } = response
        // 
        // this.token = token
        // this.userInfo = userInfo
        // this.permissions = permissions
        // 
        // // 保存到本地存储
        // localStorage.setItem('token', token)
        // localStorage.setItem('userInfo', JSON.stringify(userInfo))
        // localStorage.setItem('permissions', JSON.stringify(permissions))
        // 
        // return response
      } catch (error) {
        throw error
      }
    },
    
    // 获取用户信息
    async getUserInfo() {
      try {
        const response = await authApi.getUserInfo()
        this.userInfo = response.userInfo
        this.permissions = response.permissions
        
        localStorage.setItem('userInfo', JSON.stringify(response.userInfo))
        localStorage.setItem('permissions', JSON.stringify(response.permissions))
        
        return response
      } catch (error) {
        this.logout()
        throw error
      }
    },
    
    // 登出
    async logout() {
      // 直接清除本地数据，不调用API，避免因后端不可用而导致的错误
      this.token = ''
      this.userInfo = null
      this.permissions = []
      
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      localStorage.removeItem('permissions')
      
      // 这里注释掉API调用，因为后端可能不可用
      // 如果后端已经可用，可以取消下面的注释
      // try {
      //   await authApi.logout()
      // } catch (error) {
      //   console.error('Logout API call failed:', error)
      // }
    },
    
    // 检查权限
    hasPermission(permission) {
      if (!permission) return true
      return this.permissions.includes(permission)
    },
    
    // 检查角色
    hasRole(role) {
      if (!role) return true
      return this.roles.some(r => r.code === role)
    }
  }
})
